Ext.define('Admin.view.main.MainController', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.main',

    init: function() {
        var me = this,
            refs = me.getReferences(),
            navigationList = refs.navigationTreeList, //左侧导航栏
            topBtnList = refs.topBtnList; //顶部导航栏
        var allmenu = [];
        Ext.Ajax.request({
            url: config.URL + 'szy/sys/menu/listTree?extId=0',
            method: "post",
            success: function(response, opts) {
                allmenu = Ext.JSON.decode(response.responseText)[0].children;
                // console.log('allmenuallmenu', allmenu);
                var topItems = [];
                for (var i = 0; i < allmenu.length; i++) {
                    var topIt = {};
                    topIt.topId = allmenu[i].viewType;
                    topIt.text = allmenu[i].text;
                    topIt.iconAlign = 'top';
                    topIt.iconCls = allmenu[i].iconCls;
                    topIt.style = 'font-size:18px';
                    topIt.children = allmenu[i].children;
                    topItems.push(topIt);
                }

                topBtnList.add(topItems);

                refs.topBtnList.items.items[0].toggle(); //默认选中第一个按钮
                //me.redirectTo("map"); //刷新/进入页面默认跳转GIS地图
                //this.setCurrentView('riverBaseInfo');
                me.onRouteChange('map');

            },
            failure: function() {
                Ext.Msg.alert('系统提示', '系统出错！');
            },
            params: { river: config.RIVER }
        });
    },

    listen: {
        controller: {
            '#': {
                unmatchedroute: 'onRouteChange'
            }
        }
    },

    routes: {
        ':node': 'onRouteChange'
    },

    lastView: null,


    setCurrentView: function(hashTag) {
        hashTag = (hashTag || '').toLowerCase();
        //console.log('navigationList', this.getReferences().navigationTreeList.getStore());
        var me = this,
            refs = me.getReferences(),
            mainCard = refs.mainCardPanel,
            mainLayout = mainCard.getLayout(),
            navigationList = refs.navigationTreeList,
            store = navigationList.getStore();
        // console.log('storestorestorestorestorestorestore', store);
        var node = store.findNode('viewType', hashTag),
            view = (node && node.get('viewType')) || 'page404',
            lastView = me.lastView,
            existingItem = mainCard.child('component[viewType=' + hashTag + ']'),
            newView;
        // console.log('refs',refs)
        // console.log(navigationList)
        // Kill any previously routed window
        if (lastView && lastView.isWindow) {
            lastView.destroy();
        }

        lastView = mainLayout.getActiveItem();

        if (!existingItem) {
            newView = Ext.create({
                xtype: view,
                viewType: hashTag, // for existingItem search later
                hideMode: 'offsets'
            });
        }

        if (!newView || !newView.isWindow) {
            // !newView means we have an existing view, but if the newView isWindow
            // we don't add it to the card layout.
            if (existingItem) {
                // We don't have a newView, so activate the existing view.
                if (existingItem !== lastView) {
                    mainLayout.setActiveItem(existingItem);
                }
                newView = existingItem;
            } else {
                // newView is set (did not exist already), so add it and make it the
                // activeItem.
                Ext.suspendLayouts();
                mainLayout.setActiveItem(mainCard.add(newView));
                Ext.resumeLayouts(true);
            }
        }

        navigationList.setSelection(node);

        if (newView.isFocusable(true)) {
            newView.focus();
        }

        me.lastView = newView;
    },
    /**
     * 顶部菜单栏点击切换左边菜单事件
     */
    // onSelectTopNavInit: function () {
    //     $('#wd-top-nav-box').on('click', 'li', function () {
    //         $('#wd-top-nav-box li').removeClass('active');
    //         $(this).addClass('active');
    //
    //     });
    // },
    onMainMenuToggle: function(container, button, pressed) {
        var me = this,
            refs = me.getReferences(),
            navigationList = refs.navigationTreeList;

        var store = Ext.create('Ext.data.TreeStore', {
            fields: [{
                name: 'text'
            }],
            root: {
                expanded: true,
                children: button.children
            },
        });
        navigationList.setStore(store);

        //默认跳转第一个子菜单
        var storeData = store.getData().items;
        var getDefSelectedMenu = function(data) {
            if (data[0].childNodes && data[0].childNodes.length < 1) {
                return data[0].data.viewType || "";
            } else {
                return getDefSelectedMenu(data[0].childNodes);
            }
        };
        var defSelectedMenu = getDefSelectedMenu(storeData);
        me.redirectTo(defSelectedMenu);
    },


    onNavigationTreeSelectionChange: function(tree, node) {
        // console.log(tree, node);
        var to = node && node.get('viewType');

        if (to) {
            this.redirectTo(to);
        }
    },

    onToggleNavigationSize: function() {
        var me = this,
            refs = me.getReferences(),
            navigationList = refs.navigationTreeList,
            wrapContainer = refs.mainContainerWrap,
            collapsing = !navigationList.getMicro(),
            new_width = collapsing ? 64 : 250;

        if (Ext.isIE9m || !Ext.os.is.Desktop) {
            Ext.suspendLayouts();

            refs.senchaLogo.setWidth(new_width);

            navigationList.setWidth(new_width);
            navigationList.setMicro(collapsing);

            Ext.resumeLayouts(); // do not flush the layout here...

            // No animation for IE9 or lower...
            wrapContainer.layout.animatePolicy = wrapContainer.layout.animate = null;
            wrapContainer.updateLayout(); // ... since this will flush them
        } else {
            if (!collapsing) {
                // If we are leaving micro mode (expanding), we do that first so that the
                // text of the items in the navlist will be revealed by the animation.
                navigationList.setMicro(false);
            }
            navigationList.canMeasure = false;

            // Start this layout first since it does not require a layout
            refs.senchaLogo.animate({ dynamic: true, to: { width: new_width } });

            // Directly adjust the width config and then run the main wrap container layout
            // as the root layout (it and its chidren). This will cause the adjusted size to
            // be flushed to the element and animate to that new size.
            navigationList.width = new_width;
            wrapContainer.updateLayout({ isRoot: true });
            navigationList.el.addCls('nav-tree-animating');

            // We need to switch to micro mode on the navlist *after* the animation (this
            // allows the "sweep" to leave the item text in place until it is no longer
            // visible.
            if (collapsing) {
                navigationList.on({
                    afterlayoutanimation: function() {
                        navigationList.setMicro(true);
                        navigationList.el.removeCls('nav-tree-animating');
                        navigationList.canMeasure = true;
                    },
                    single: true
                });
            }
        }
    },

    onMainViewRender: function() {
        if (!window.location.hash) {
            this.redirectTo("needWater");
        }
    },

    onRouteChange: function(id) {
        // console.log('切换了页面：', id);
        var idd = id.split("?")[0];
        this.setCurrentView(idd);
    },

    // onSearchRouteChange: function() {
    //     this.setCurrentView('searchresults');
    // },

    onSwitchToModern: function() {
        Ext.Msg.confirm('Switch to Modern', 'Are you sure you want to switch toolkits?',
            this.onSwitchToModernConfirmed, this);
    },

    onSwitchToModernConfirmed: function(choice) {
        if (choice === 'yes') {
            var s = window.location.search;

            // Strip "?classic" or "&classic" with optionally more "&foo" tokens
            // following and ensure we don't start with "?".
            s = s.replace(/(^\?|&)classic($|&)/, '').replace(/^\?/, '');

            // Add "?modern&" before the remaining tokens and strip & if there are
            // none.
            window.location.search = ('?modern&' + s).replace(/&$/, '');
        }
    },

    // onEmailRouteChange: function() {
    //     this.setCurrentView('email');
    // }
});